/* eslint-disable no-return-assign */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import {
  getNestedRoutePath,
  route2routePath,
  useControlController,
  useNamespace,
} from '@ibiz-template/vue3-util';
import { computed, defineComponent, PropType, ref, watch } from 'vue';
import { IAppDETabExplorerView, ITabExpPanel } from '@ibiz/model-core';
import {
  IControlProvider,
  TabExpPanelController,
} from '@ibiz-template/runtime';
import { useRoute } from 'vue-router';
import './tab-exp-panel-dropdown.scss';

export const TabExpPanelDropdownControl = defineComponent({
  name: 'TabExpPanelDropdownControl',
  props: {
    modelData: { type: Object as PropType<ITabExpPanel>, required: true },
    context: { type: Object as PropType<IContext>, required: true },
    params: { type: Object as PropType<IParams>, default: () => ({}) },
    provider: { type: Object as PropType<IControlProvider> },
    defaultTabName: { type: String, required: false },
  },
  setup() {
    const c = useControlController(
      (...args) => new TabExpPanelController(...args),
    );
    const ns = useNamespace(
      `control-${c.model.controlType!.toLowerCase()}-dropdown`,
    );

    const visible = ref(false);

    const tabPosition =
      (c.view.model as IAppDETabExplorerView).tabLayout?.toLowerCase() || 'top';

    const route = useRoute();

    let expViewRoutePath = '';
    if (c.routeDepth) {
      expViewRoutePath = getNestedRoutePath(route, c.routeDepth);
    }

    const activeItem = computed(() => {
      return c.state.tabPages.find(v => v.tabTag === c.state.activeName);
    });

    const handleClick = (tab: string) => {
      if (tab !== c.state.activeName) {
        c.state.activeName = tab;
        c.handleTabChange();
      }
    };

    watch(
      () => route.fullPath,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          const depth = c.routeDepth;
          if (depth) {
            const currentRoutePath = getNestedRoutePath(route, c.routeDepth);
            if (currentRoutePath === expViewRoutePath) {
              const routePath = route2routePath(route);
              const { srfnav } = routePath.pathNodes[depth! - 1];
              if (
                srfnav &&
                c.state.activeName &&
                c.state.activeName !== srfnav
              ) {
                c.state.activeName = srfnav;
                c.handleTabChange();
              }
            }
          }
        }
      },
      { immediate: true },
    );

    // 是否显示下拉列表
    const isShow = ref(false);

    // 视图codename数组
    const showTabExpPanelDropdownList = (ibiz.env as IData)
      ?.showTabExpPanelDropdownList;

    if (showTabExpPanelDropdownList) {
      const list: string[] = JSON.parse(showTabExpPanelDropdownList);
      if (Array.isArray(list)) {
        const codeName = c.view?.model?.codeName;
        if (codeName) {
          isShow.value = list.includes(codeName);
        }
      }
    }

    return {
      c,
      ns,
      visible,
      activeItem,
      tabPosition,
      isShow,
      handleClick,
    };
  },
  render() {
    const { isCreated, tabPages } = this.c.state;
    if ((ibiz.env as IData).simplemode && !this.isShow) {
      return null;
    }
    return (
      <iBizControlBase controller={this.c} class={this.ns.b()}>
        {isCreated && (
          <el-dropdown
            trigger='click'
            popper-class={this.ns.b()}
            onVisibleChange={(state: boolean) => (this.visible = state)}
            onCommand={(command: string) => this.handleClick(command)}
          >
            {{
              default: () => (
                <el-button class={this.ns.e('button')}>
                  {this.activeItem && [
                    <iBizIcon icon={this.activeItem.sysImage}></iBizIcon>,
                    <span class={this.ns.e('caption')}>
                      {this.activeItem.caption}
                    </span>,
                  ]}
                  {this.visible ? (
                    <ion-icon name='chevron-up-outline'></ion-icon>
                  ) : (
                    <ion-icon name='chevron-down-outline'></ion-icon>
                  )}
                </el-button>
              ),
              dropdown: () => (
                <el-dropdown-menu>
                  {tabPages.map(tab => {
                    return (
                      <el-dropdown-item
                        class={[
                          this.ns.e('item'),
                          this.ns.is(
                            'active',
                            this.c.state.activeName === tab.tabTag,
                          ),
                        ]}
                        title={tab.caption}
                        command={tab.tabTag}
                      >
                        {tab.sysImage && (
                          <iBizIcon icon={tab.sysImage}></iBizIcon>
                        )}
                        {tab.caption}
                      </el-dropdown-item>
                    );
                  })}
                </el-dropdown-menu>
              ),
            }}
          </el-dropdown>
        )}
      </iBizControlBase>
    );
  },
});
